package com.ncepu.clubmanagement.controller;

import com.ncepu.clubmanagement.pojo.MessageFont;
import com.ncepu.clubmanagement.pojo.MessageMetaData;
import com.ncepu.clubmanagement.pojo.Result;
import com.ncepu.clubmanagement.service.MessageService;
import com.ncepu.clubmanagement.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
@RequestMapping("/message")
public class MessageController {

    @Autowired
    private MessageService messageService;

    @Autowired
    private JwtUtils jwtUtil;

    @Autowired
    private HttpServletRequest request;


    @PostMapping()
    public Result sendMessage(@RequestBody MessageFont messageFont) throws Exception {
        log.info("发送消息");

        // jwt 获取发送者
        String jwt = request.getHeader("token");
        Claims claims = jwtUtil.parseJWT(jwt);
        Integer sourcePersonId = (Integer) claims.get("id");
        messageFont.setSourcePersonId(sourcePersonId);

        messageService.sendMessage(messageFont);
        return Result.success();
    }

    @GetMapping("/self")
    public Result getSelfMessageList(){
        log.info("获取消息");

        // jwt 获取发送者
        String jwt = request.getHeader("token");
        Claims claims = jwtUtil.parseJWT(jwt);
        Integer sourcePersonId = (Integer) claims.get("id");

        List<MessageMetaData> metaDataList = messageService.getMessageMetaDataList(sourcePersonId);
        return Result.success(metaDataList);

    }

    @PutMapping()
    public Result setMessageIsRead(Integer messageId){
        log.info("设置消息已读");

        // jwt 获取发送者
        String jwt = request.getHeader("token");
        Claims claims = jwtUtil.parseJWT(jwt);
        Integer targetPersonId = (Integer) claims.get("id");

        messageService.setMessageIsReadWithVerifyPermission(messageId, targetPersonId);
        return Result.success();
    }

    @GetMapping("/content")
    public Result getMessageContent(Integer messageId){
        log.info("获取消息内容");

        // jwt 获取发送者
        String jwt = request.getHeader("token");
        Claims claims = jwtUtil.parseJWT(jwt);
        Integer targetPersonId = (Integer) claims.get("id");

        String content = messageService.getMessageContent(messageId, targetPersonId);
        return Result.success(content);

    }
}
